<template>
    <div>
        <el-form
            ref="dataForm"
            :model="dataForm"
            label-width="8em"
            :rules="dataFormRule"
            class="table-edit-from"
        >
            <div v-show="first">
                <el-form-item label="组卷规则名称" prop="ruleName">
                    <el-input v-model="dataForm.ruleName"></el-input>
                </el-form-item>
                <el-form-item label="考试分类" prop="paperType">
                    <div class="table-query-input">
                        <el-select
                            v-model="dataForm.paperType"
                            placeholder="请选择考试类型"
                            :disabled="!addAction"
                        >
                            <el-option
                                label="章节测试"
                                value="chapterText"
                            ></el-option>
                            <el-option
                                label="期末考试"
                                value="finalExam"
                            ></el-option>
                            <el-option
                                label="普通考试"
                                value="normalExam"
                            ></el-option>
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="组卷方式" prop="ruleType">
                    <el-radio
                        v-model="dataForm.ruleType"
                        :disabled="!addAction"
                        label="random"
                        >随机组卷</el-radio
                    >
                    <el-radio
                        v-model="dataForm.ruleType"
                        :disabled="!addAction"
                        label="select"
                        >抽题组卷</el-radio
                    >
                </el-form-item>
                <el-form-item label="题库" prop="ruleType">
                    <el-radio
                        v-model="dataForm.sourceType"
                        disabled
                        label="personalQuestion"
                        >个人题库</el-radio
                    >
                    <el-radio
                        v-model="dataForm.sourceType"
                        disabled
                        label="vipQuestion"
                        >维普题库</el-radio
                    >
                </el-form-item>
                <div>
                    <el-form-item label="关联学科" prop="classificationId">
                        <el-cascader
                            v-model="dataForm.classificationId"
                            :options="classificationInfo"
                            :show-all-levels="false"
                            filterable
                            clearable
                            :props="{
                                value: 'id',
                                label: 'name',
                                emitPath: false,
                                checkStrictly: true
                            }"
                            @change="handleClassficationId"
                        ></el-cascader>
                    </el-form-item>
                    <!--                期末考试 关联课程-->
                    <el-form-item
                        v-if="dataForm.paperType !== 'normalExam'"
                        label="关联课程"
                        prop="courseId"
                    >
                        <div class="table-query-input">
                            <el-cascader
                                ref="courseRef"
                                v-model="dataForm.courseId"
                                v-loading="flag.course"
                                :options="courseInfo"
                                placeholder="请选择课程"
                                :show-all-levels="false"
                                clearable
                                filterable
                                :props="{
                                    value: 'id',
                                    label: 'courseName',
                                    emitPath: false,
                                    checkStrictly: true
                                }"
                            >
                            </el-cascader>
                        </div>
                    </el-form-item>
                    <!--                章节测试 关联章节-->
                    <!--                    <el-form-item v-if="dataForm.paperType==='chapterText'" label="关联章节" prop="chapterId">-->
                    <!--                        <div class="table-query-input">-->
                    <!--                            <el-cascader-->
                    <!--                                ref="chapterRef"-->
                    <!--                                v-model="dataForm.chapterId"-->
                    <!--                                v-loading="flag.chapter"-->
                    <!--                                :options="chapterInfo"-->
                    <!--                                placeholder="请选择章节"-->
                    <!--                                :show-all-levels="false"-->
                    <!--                                clearable-->
                    <!--                                filterable-->
                    <!--                                :props="{-->
                    <!--                                value: 'id',-->
                    <!--                                label: 'name',-->
                    <!--                                emitPath: false,-->
                    <!--                                checkStrictly: true-->
                    <!--                            }"-->
                    <!--                            >-->
                    <!--                            </el-cascader>-->
                    <!--                        </div>-->
                    <!--                    </el-form-item>-->
                </div>
                <el-form-item label="组卷描述" prop="remark">
                    <el-input
                        v-model="dataForm.remark"
                        type="textarea"
                        :rows="3"
                        :disabled="dataForm.system"
                    ></el-input>
                </el-form-item>
                <el-button
                    type="primary"
                    :loading="submitFlag"
                    @click="goSecond()"
                >
                    下一步
                </el-button>
            </div>

            <div v-show="second">
                <el-container>
                    <el-aside width="300px">
                        <div class="paperTotal">
                            <div style="margin-top: 20px">
                                总题数: {{ dataForm.totalNum || 0 }} 题
                            </div>
                            <div>总分数: {{ dataForm.totalScore || 0 }} 分</div>
                        </div>
                        <div
                            v-for="(items, index) in contentList"
                            :key="index"
                            class="questionNum"
                        >
                            <div style="margin-top: 20px">
                                <div>
                                    <span>{{ items.desc }}</span>
                                    <el-button
                                        type="danger"
                                        style="margin-left: 10px;"
                                        size="mini"
                                        icon="el-icon-delete"
                                        circle
                                        @click="removeQuestion(index)"
                                    ></el-button>
                                </div>
                                <span>
                                    共 {{ items.num }} 题 共
                                    {{ items.score }} 分</span
                                >
                            </div>
                        </div>
                    </el-aside>
                    <el-container>
                        <el-header>
                            <div style="margin-top: 20px">
                                {{ dataForm.ruleName }}
                            </div>
                        </el-header>
                        <el-main>
                            <div
                                v-for="(item, index) in contentList"
                                :key="index"
                                class="questionData"
                            >
                                <div style="line-height: 50px;">
                                    <el-input
                                        v-model="item.desc"
                                        placeholder="请输入内容"
                                        style="margin-left: -450px;"
                                    ></el-input>
                                    <span style="margin-left: 100px;">
                                        {{ status[item.firstType] }}</span
                                    >
                                </div>
                                <div style="height: 50px;">
                                    <span>
                                        难度: 简单: {{ item.easyNum }} 分数:{{
                                            item.easyScore
                                        }};
                                    </span>
                                    <span>
                                        普通: {{ item.normalNum }} 分数:{{
                                            item.normalScore
                                        }};</span
                                    >
                                    <span>
                                        困难: {{ item.diffcultNum }} 分数:{{
                                            item.diffcultScore
                                        }};</span
                                    >
                                </div>
                            </div>
                            <div>
                                <el-button
                                    type="primary"
                                    plain
                                    @click="toQuestionlist('singleChoice')"
                                    >单选题</el-button
                                >
                                <el-button
                                    type="primary"
                                    plain
                                    @click="toQuestionlist('multipleChoice')"
                                    >多选题
                                </el-button>
                                <el-button
                                    type="primary"
                                    plain
                                    @click="toQuestionlist('judgment')"
                                    >判断题</el-button
                                >
                                <el-button
                                    type="primary"
                                    plain
                                    @click="toQuestionlist('fill')"
                                    >填空题</el-button
                                >
                                <el-button
                                    type="primary"
                                    plain
                                    @click="toQuestionlist('text')"
                                    >简答题</el-button
                                >
                                <el-button
                                    type="primary"
                                    plain
                                    @click="toQuestionlist('combination')"
                                    >组合题</el-button
                                >
                            </div>
                        </el-main>
                    </el-container>
                </el-container>
                <el-button
                    type="primary"
                    :loading="submitFlag"
                    @click="goFirst()"
                >
                    上一步
                </el-button>
                <el-button
                    type="primary"
                    :loading="submitFlag"
                    @click="goThird()"
                >
                    下一步
                </el-button>
            </div>
            <div v-show="third">
                <el-form-item label="组卷名称" prop="ruleName">
                    <el-input v-model="dataForm.ruleName"></el-input>
                </el-form-item>
                <el-form-item label="考试分类" prop="paperType">
                    <div class="table-query-input">
                        <el-select
                            v-model="dataForm.paperType"
                            placeholder="请选择考试类型"
                            disabled
                        >
                            <el-option
                                label="章节测试"
                                value="chapterText"
                            ></el-option>
                            <el-option
                                label="期末考试"
                                value="finalExam"
                            ></el-option>
                            <el-option
                                label="普通考试"
                                value="normalExam"
                            ></el-option>
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="组卷方式" prop="ruleType">
                    <el-radio
                        v-model="dataForm.ruleType"
                        disabled
                        label="random"
                        >随机组卷</el-radio
                    >
                    <el-radio
                        v-model="dataForm.ruleType"
                        disabled
                        label="select"
                        >抽题组卷</el-radio
                    >
                </el-form-item>

                <el-form-item label="组卷描述" prop="remark">
                    <el-input
                        v-model="dataForm.remark"
                        type="textarea"
                        :rows="3"
                        :disabled="dataForm.system"
                    ></el-input>
                </el-form-item>
                <el-form-item label="试卷总分" prop="totalScore">
                    <el-input
                        v-model.number="dataForm.totalScore"
                        disabled
                    ></el-input>
                </el-form-item>
                <el-form-item label="试卷及格分" prop="passScore">
                    <el-input v-model.number="dataForm.passScore"></el-input>
                </el-form-item>
                <el-button
                    type="primary"
                    :loading="submitFlag"
                    @click="goSecond()"
                >
                    上一步
                </el-button>
                <el-button
                    type="primary"
                    :loading="submitFlag"
                    @click="save('/exam/rule/updateContent')"
                >
                    保存
                </el-button>
            </div>
        </el-form>

        <el-dialog
            title="添加试题"
            :visible.sync="contentDialogVisible"
            width="40%"
        >
            <el-form
                ref="contentForm"
                :inline="true"
                :model="initContent"
                label-width="100px"
                :rules="contentFormRule"
            >
                <el-form-item label="简单题数量" prop="easyNum">
                    <el-input
                        v-model.number="initContent.easyNum"
                        style="width: 50%"
                    ></el-input>
                    <span>/{{ questionNum.easyNum }}</span>
                </el-form-item>
                <el-form-item label="分数" prop="easyScore">
                    <el-input v-model.number="initContent.easyScore"></el-input>
                </el-form-item>
                <el-form-item label="普通题数量" prop="normalNum">
                    <el-input
                        v-model.number="initContent.normalNum"
                        style="width: 50%"
                    ></el-input>
                    <span>/{{ questionNum.normalNum }}</span>
                </el-form-item>
                <el-form-item label="分数" prop="normalScore">
                    <el-input
                        v-model.number="initContent.normalScore"
                    ></el-input>
                </el-form-item>
                <el-form-item label="困难题数量" prop="diffcultNum">
                    <el-input
                        v-model.number="initContent.diffcultNum"
                        style="width: 50%"
                    ></el-input>
                    <span>/{{ questionNum.diffcultNum }}</span>
                </el-form-item>
                <el-form-item label="分数" prop="diffcultScore">
                    <el-input
                        v-model.number="initContent.diffcultScore"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button
                    :loading="contentsubmitFlag"
                    @click="contentDialogClose"
                    >取 消</el-button
                >
                <el-button
                    :loading="contentsubmitFlag"
                    type="primary"
                    @click="contentDataSave"
                    >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { TablePage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import { get, post, put } from "@/api/request";
import { beanCopy, treeList2Tree } from "@/utils";
import { fetchRuleId, getQuestionCount } from "@/api/exam";
import {
    fetchChapterList,
    fetchClassificationChildren,
    fetchClassificationFirst,
    fetchClassificationList2,
    fetchCourseList
} from "@/api/course";

export default {
    name: "AddRule",
    components: {},
    mixins: [TablePage],
    data() {
        return {
            flag: {
                classfication: false,
                course: false,
                chapter: false
            },
            courseQueryData: {
                size: 1000,
                courseSubjectId: ""
            },
            chapterQueryData: {
                size: 1000,
                baseCourseId: ""
            },
            classficationQueryData: {
                size: 1000
            },
            currentClassificationId: null,
            key: 0,
            classificationProps: {
                lazy: true,
                checkStrictly: true,
                emitPath: false,
                lazyLoad: this.getClassification
            },
            courseInfo: [],
            chapterInfo: [],
            classificationInfo: [],
            addAction: true,
            fromExam: false,
            contentsubmitFlag: false,
            contentDialogVisible: false,
            selectQuestionparams: {
                isHide: false,
                queryType: 1
            },
            initContent: {
                firstType: "",
                diffcultNum: 0,
                normalNum: 0,
                easyNum: 0,
                everyScore: 5,
                sourceType: 2,
                easyScore: 5,
                normalScore: 5,
                diffcultScore: 5
            },
            contentList: [],
            first: true,
            second: false,
            third: false,
            hasDone: false,
            questionNum: {
                easyNum: 0,
                normalNum: 0,
                diffcultNum: 0
            },
            dataForm: {
                paperType: "",
                content: [],
                totalNum: 0,
                totalScore: 0,
                passScore: 0,
                sourceType: "vipQuestion"
            },

            initAddForm: {
                id: null,
                name: null,
                remark: null,
                actionCodes: []
            },
            actions: null,
            actionSearch: null,
            src:
                "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg",
            dataFormRule: {
                ruleName: [
                    {
                        required: true,
                        message: "请输入组卷名称",
                        trigger: "blur"
                    }
                ],
                paperType: [
                    {
                        required: true,
                        message: "请选择考试类型",
                        trigger: "change"
                    }
                ],
                ruleType: [
                    {
                        required: true,
                        message: "请选择组卷方式",
                        trigger: "change"
                    }
                ],
                classificationId: [
                    { required: true, message: "请选择科目", trigger: "change" }
                ]
            },
            contentFormRule: {
                easyNum: [{ required: true, message: "不能为空" }],
                normalNum: [{ required: true, message: "不能为空" }],
                diffcultNum: [{ required: true, message: "不能为空" }],
                easyScore: [{ required: true, message: "分数不能为空" }],
                normalScore: [{ required: true, message: "分数不能为空" }],
                diffcultScore: [{ required: true, message: "分数不能为空" }]
            }
        };
    },
    computed: {
        ...mapState({
            status: state => state.status.questionFirstType
        })
    },
    watch: {
        actionSearch(val) {
            this.$refs.tree.filter(val);
        },
        $route: function(to, from) {
            this.initdata();
        }
    },
    mounted() {
        this.initdata();
    },
    methods: {
        search() {
            this.getClassfication();
        },
        initdata() {
            if (this.$route.query.ruleId) {
                this.addAction = false;
                fetchRuleId({ id: this.$route.query.ruleId }).then(res => {
                    this.dataForm = res;
                    if (res.classificationId) {
                        this.handleClassficationId(
                            this.dataForm.classificationId
                        );
                    }
                    if (res.courseId) {
                        this.handleChapterId(this.dataForm.courseId);
                    }
                });
            } else {
                this.addAction = true;
                this.dataForm.sourceType = "vipQuestion";
            }
        },
        //获取学科
        getClassification(node, resolve) {
            const { level } = node;
            let disable = false;
            if (!node.data) {
                fetchClassificationFirst().then(res => {
                    if (res !== null) {
                        const nodes = Array.from(res).map(item => {
                            disable =
                                this.currentClassificationId !== null &&
                                item.id === this.currentClassificationId;
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >= (item.children.length > 0 ? 1 : 0),
                                disabled: disable
                            };
                        });
                        resolve(nodes);
                    }
                });
            } else {
                fetchClassificationChildren({ id: node.data.value }).then(
                    res => {
                        const nodes = Array.from(res).map(item => {
                            disable =
                                (this.currentClassificationId !== null &&
                                    item.id === this.currentClassificationId) ||
                                this.currentClassificationId === item.parentId;
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >=
                                    (item.children.length > 0 ? level + 1 : 0),
                                disabled: disable
                            };
                        });
                        resolve(nodes);
                    }
                );
            }
        },
        getClassfication() {
            fetchClassificationList2(this.classficationQueryData).then(res => {
                this.classificationInfo = treeList2Tree(res);
            });
        },
        //获取选中学科 查询课程
        handleClassficationId(value) {
            this.flag.course = true;
            this.courseQueryData.courseSubjectId = value;
            fetchCourseList(this.courseQueryData, "查询课程信息异常").then(
                res => {
                    this.courseInfo = treeList2Tree(res);
                    this.flag.course = false;
                }
            );
        },
        //根据课程id查询章节id
        handleChapterId(value) {
            this.flag.chapter = true;
            this.chapterQueryData.courseId = value;
            fetchChapterList(this.chapterQueryData, "查询章节信息异常").then(
                res => {
                    this.chapterInfo = treeList2Tree(res);
                    this.flag.chapter = false;
                }
            );
        },
        goFirst() {
            this.first = true;
            this.second = false;
            this.third = false;
        },
        goSecond() {
            this.$refs.dataForm.validate(valid => {
                if (valid) {
                    this.submitFlag = true;
                    const promise = this.addAction
                        ? post("/exam/rule/update", this.dataForm)
                        : put("/exam/rule/update", this.dataForm);
                    promise
                        .then(res => {
                            this.addAction = false;
                            this.dataForm = res;
                            this.$route.query.ruleId = res.id;
                            beanCopy(
                                this.dataForm.content,
                                this.contentList,
                                true
                            );
                            this.changeNum();
                            this.first = false;
                            this.second = true;
                            this.third = false;
                        })
                        .finally(() => {
                            this.submitFlag = false;
                        });
                } else {
                    return false;
                }
            });
        },
        goThird() {
            this.first = false;
            this.second = false;
            this.third = true;
        },
        toQuestionlist(data) {
            this.initContent = {
                firstType: "",
                desc: "",
                diffcultNum: 0,
                normalNum: 0,
                easyNum: 0,
                easyScore: 5,
                normalScore: 5,
                diffcultScore: 5
            };
            this.selectQuestionparams.classificationId = this.dataForm.classificationId;
            this.selectQuestionparams.sourceType = this.dataForm.sourceType;
            this.selectQuestionparams.firstType = data;
            this.initContent.firstType = data;
            this.initContent.desc = this.status[data];
            this.contentDialogVisible = true;
            this.getQuestionNum();
        },
        getQuestionNum() {
            getQuestionCount(
                this.selectQuestionparams,
                "查询试题数量异常"
            ).then(res => {
                this.questionNum.easyNum = res[0];
                this.questionNum.normalNum = res[1];
                this.questionNum.diffcultNum = res[2];
            });
        },
        changeNum() {
            let totalNum = 0;
            let totalScore = 0;
            this.contentList.forEach(item => {
                let num = 0;
                let easyNum = 0;
                let normalNum = 0;
                let diffcultNum = 0;
                let score = 0;

                easyNum = parseInt(item.easyNum);
                normalNum = parseInt(item.normalNum);
                diffcultNum = parseInt(item.diffcultNum);
                num = diffcultNum + normalNum + easyNum;
                item.num = num;
                score =
                    easyNum * parseInt(item.easyScore) +
                    normalNum * parseInt(item.normalScore) +
                    diffcultNum * parseInt(item.diffcultScore);
                item.score = score;
                totalNum += num;
                totalScore += score;
            });
            this.dataForm.totalScore = totalScore;
            this.dataForm.totalNum = totalNum;
            this.dataForm.passScore = parseInt(totalScore * 0.6);
        },
        removeQuestion(index) {
            this.contentList.splice(index, 1);
            this.changeNum();
        },
        contentDialogClose() {
            this.contentDialogVisible = false;
        },
        contentDataSave() {
            if (
                this.initContent.easyNum < 0 ||
                this.initContent.easyNum > this.questionNum.easyNum
            ) {
                this.$alert("简单题数量不对,请重新填写");
                return false;
            }
            if (
                this.initContent.normalNum < 0 ||
                this.initContent.normalNum > this.questionNum.normalNum
            ) {
                this.$alert("普通题数量不对,请重新填写");
                return false;
            }
            if (
                this.initContent.diffcultNum < 0 ||
                this.initContent.diffcultNum > this.questionNum.diffcultNum
            ) {
                this.$alert("困难题数量不对,请重新填写");
                return false;
            }
            if (this.initContent.everyScore < 0) {
                this.$alert("每题分数大小不对,请重新填写");
                return false;
            }
            this.$refs.contentForm.validate(valid => {
                if (valid) {
                    this.contentsubmitFlag = true;
                    let obj = {};
                    beanCopy(this.initContent, obj, true);
                    this.initContent = {};
                    this.contentList.push(obj);
                    this.contentDialogVisible = false;
                    this.changeNum();
                    this.contentsubmitFlag = false;
                } else {
                    this.contentsubmitFlag = false;
                    return false;
                }
            });
        },
        save(url) {
            this.$refs.dataForm.validate(valid => {
                if (valid) {
                    this.submitFlag = true;
                    this.dataForm.content = this.contentList;
                    const promise = put(url, this.dataForm);
                    return promise
                        .then(res => {
                            this.$store.dispatch(
                                "tagsView/delView",
                                this.$route
                            );
                            this.$router.go(-1);
                            // this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
                            // this.$router.push(this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.length - 1].path)
                            //this.$alert("保存成功", "提示")
                        })
                        .finally(() => {
                            this.submitFlag = false;
                        });
                } else {
                    return false;
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.container {
    background: #fff;
    border-radius: 0.3em 0.3em 0 0;
    padding-bottom: 1em;
    padding-top: 1em;
    padding-left: 1em;
    margin-top: 16px;

    .container-content {
        padding-top: 12px;

        p {
            color: #909399;
            font-size: 15px;
            padding-top: 12px;
        }
    }

    .container-right {
        margin-left: 12px;
        margin-top: 2em;

        .r-img {
            max-width: 240px;
            max-height: 160px;
        }

        .r-btn {
            margin-top: 22px;
        }
    }
}

.table-search-box {
    padding-left: 17px;
    font-size: 16px;
}

::v-deep .el-header {
    background-color: #fff;
    color: #333;
    text-align: center;
    height: 60px;
}

::v-deep .el-aside {
    background-color: #fff;
    color: #333;
    text-align: center;
}

::v-deep .el-main {
    background-color: #e9eef3;
    color: #333;
    text-align: center;
}

.questionData {
    background-color: #f5f7fa;
    margin-top: 10px;
}
.questionNum {
    background-color: #fff;
    border: 1px solid #ebeef5;
    height: 80px;
    margin-top: 10px;
}

body > .el-container {
    margin-bottom: 40px;
}

.paperTotal {
    background: aliceblue;
}
</style>
